package uc.contancts;

import java.util.ArrayList;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import co.chuangdian.oflauncher.R;

public class ContanctAdapter extends BaseAdapter {
	
	private Context mContext;
	private ArrayList<Contanct> allContact=new  ArrayList<Contanct>();
	ArrayList<String> contanctsIds=new  ArrayList<String>();

	public ContanctAdapter(Context mContext, ArrayList<Contanct> allContact) {
		this.mContext = mContext;
		this.allContact = allContact;
		//contanctsIds=ContanctsInfo.getContanctsIds(mContext);
	}

	@Override
	public int getCount() {
		return allContact.size();
	}

	@Override
	public Object getItem(int position) {
		return allContact.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		View view = convertView;
		if (convertView == null) {
			view = View.inflate(mContext, R.layout.contancts_item_list, null);

		}
		ViewHolder mViewHolder = ViewHolder.getHolder(view);

		Contanct contancts = allContact.get(position);

		String str = null;
		String currentLetter = contancts.getPinyin().charAt(0) + "";
		// 根据上一个首字母,决定当前是否显示字母
		if (position == 0) {
			str = currentLetter;
		} else {
			// 上一个人的拼音的首字母
			String preLetter = allContact.get(position - 1).getPinyin().charAt(0) + "";
			// 判断两个字符串 是否相等。
			if (!TextUtils.equals(preLetter, currentLetter)) {
				str = currentLetter;
			}
		}

		// 根据str是否为空,决定是否显示索引栏
		mViewHolder.mIndex.setVisibility(str == null ? View.GONE : View.VISIBLE);
		mViewHolder.mIndex.setText(currentLetter);
		mViewHolder.mName.setText(contancts.getName());
		mViewHolder.mNumber.setText(contancts.getNumber());
		mViewHolder.mPick.setChecked(contanctsIds.contains(contancts.getId()));
		
		return view;
	}

	static class ViewHolder {
		TextView mIndex;
		TextView mName;
		TextView mNumber;
		CheckBox mPick;

		public static ViewHolder getHolder(View view) {
			Object tag = view.getTag();
			if (tag != null) {
				return (ViewHolder) tag;
			} else {
				ViewHolder viewHolder = new ViewHolder();
				viewHolder.mIndex = (TextView) view.findViewById(R.id.tv_index);
				viewHolder.mName = (TextView) view.findViewById(R.id.tv_name);
				viewHolder.mNumber = (TextView) view.findViewById(R.id.tv_number);
				viewHolder.mPick = (CheckBox) view.findViewById(R.id.cb_pick);
				view.setTag(viewHolder);
				return viewHolder;
			}

		}

	}


}
